package base

import (
	"context"
	"sync"

	"github.com/gin-gonic/gin"
	"github.com/liyaozong/mengo/common/di"

	"github.com/liyaozong/mengo/contracts/common"

	commonController "github.com/liyaozong/mengo/core/base/controller/http"
	deviceController "github.com/liyaozong/mengo/core/device/controller/http"
)

type Router struct {
	engine      *gin.Engine
	serviceName string
}

func NewBootstrap(serviceName string) *Router {
	gin.SetMode(gin.ReleaseMode)

	return &Router{
		engine:      gin.Default(),
		serviceName: serviceName,
	}
}

func (r *Router) Run(addr string) {
	// r.engine.RunTLS(addr, "resource/cert/server.crt", "resource/cert/server.key")
	r.engine.Run(addr)
}

func (b *Router) BootstrapHandler(ctx context.Context, wg *sync.WaitGroup, dic *di.Container) bool {
	// 静态web
	b.engine.StaticFile("/", "../../web/dist/index.html")
	b.engine.StaticFile("/avatar2.jpg", "../../web/dist/avatar2.jpg")
	b.engine.StaticFile("/logo.png", "../../web/dist/logo.png")
	b.engine.Static("/css", "../../web/dist/css")
	b.engine.Static("/img", "../../web/dist/img")
	b.engine.Static("/js", "../../web/dist/js")

	publicRouter := b.engine.Group("")

	// Common
	cc := commonController.NewCommonController(dic, b.serviceName)
	{
		publicRouter.GET(common.ApiPingRoute, cc.Ping)
		publicRouter.GET(common.ApiVersionRoute, cc.Version)
		publicRouter.GET(common.ApiConfigRoute, cc.Config)
	}

	// auth
	auth := commonController.NewAuthController(dic, b.serviceName)
	{
		publicRouter.POST(common.ApiLoginRoute, auth.Login)
		publicRouter.POST(common.ApiLogoutRoute, auth.Logout)
		publicRouter.POST(common.ApiTwoStepCodeRoute, auth.TwoStepCode)
	}

	// user
	user := commonController.NewUserController(dic, b.serviceName)
	{
		publicRouter.GET(common.ApiUserInfoRoute, user.UserInfo)
	}

	// Device
	d := deviceController.NewDeviceController(dic)
	publicRouter.POST(common.ApiDeviceRoute, d.AddDevice)

	return true
}
